"""  序列化器
在应用目录下构建`serializers.py`，参考`Model`类`Employee`编写`EmpSerializer`。
"""
from rest_framework import serializers
from .models import Employee
class EmpSerializer(serializers.Serializer):
	emp_no = serializers.IntegerField()
	birth_date = serializers.DateField()
	first_name = serializers.CharField(max_length=14) # max_length反序列化验证用
	last_name = serializers.CharField(max_length=16)
	gender = serializers.ChoiceField(choices=Employee.Gender.choices)
	hire_date = serializers.DateField()

	def create(self, validated_data):  # instance没给是None
		return Employee.objects.create(**validated_data)

	def update(self, instance, validated_data):  # instance为None 则执行update 见sava方法
		instance.first_name = validated_data.get('first_name', instance.first_name)
		instance.last_name = validated_data.get('last_name', instance.last_name)
		instance.email = validated_data.get('email', instance.email)
		instance.content = validated_data.get('content', instance.content)
		instance.created = validated_data.get('created', instance.created)
		instance.save()  # sql update   model类的instance
		return instance
print('~' * 30)
print(EmpSerializer()) # 打印看看效果
print('~' * 30)



from rest_framework import serializers
from .models import Employee
# ModelSerializer
class EmpSerializer10(serializers.ModelSerializer): ## 继承ModelSerializer
	class Meta:
		model = Employee  # 参照哪个model类生成字段
		# fields = ['emp_no', 'first_name', 'last_name']  # 指定字段
		fields = '__all__'  # 使用model的哪些字段
		read_only_fields = ['hire_date']  # 单独指定readonly字段


print('~' * 30)
print(EmpSerializer10())
print('~' * 30)


